package com.caigou.modules.personal.ui.board

import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.widget.ReportDialog
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.databinding.ActivityCommentDetailBinding
import com.caigou.modules.personal.R
import com.caigou.modules.personal.adapter.CommentDetailItemAdapter
import com.caigou.modules.personal.bean.BoardItemBean
import com.caigou.modules.personal.viewmodel.BoardViewModel
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/04
 */
@Route(path = RouterPath.Personal.PAGE_PERSONAL_BOARD_DETAIL)
@AndroidEntryPoint
class BoardDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityCommentDetailBinding
    private val boardViewModel: BoardViewModel by viewModels()
    private val reportViewModel: ReportViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.USER_ID)
    var boardUserId: String = ""

    @JvmField
    @Autowired(name = AppConstants.COMMENT_ID)
    var boardId: Int = 0

    private val mAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    private val itemAdapter: CommentDetailItemAdapter by lazy {
        CommentDetailItemAdapter(this, mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCommentDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.commentDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.commentDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchBoardDetailList()
            }
        }

        binding.commentDetailRecyclerView.run {
            layoutManager = LinearLayoutManager(this@BoardDetailActivity)
            adapter = itemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@BoardDetailActivity))
        }
        itemAdapter.setOnItemChildClickListener { _, view, position ->
            val bean = itemAdapter.getItem(position)
            when (view.id) {
                R.id.item_comment_detail_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, bean.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_detail_tv_report->{
                    if (AppBackgroundInfo.instance.hasLogin) {
                        with(ReportDialog(this)) {
                            btnConfirm.setOnClickListener {
                                if (TextUtils.isEmpty(reportCause)) {
                                    showToast("举报原因不能为空！")
                                    return@setOnClickListener
                                }
                                reportViewModel.setPostReport(
                                    AppBackgroundInfo.instance.userBean!!.userId, bean.replyUserInfoVo.userId,
                                    reportCause, bean.id, 1
                                )
                                dismiss()
                            }
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.commentDetailTvBack.setOnClickListener {
            finish()
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchBoardDetailList()
        }

        fetchBoardDetailList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(boardViewModel.boardDetailLiveData, ::handleGetBoardDetailList)
    }

    private fun handleGetBoardDetailList(result: Resource<BoardItemBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取留言板详情异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }
                handleBoardDetailUI(result.data!!)
            }
        }
    }

    private fun handleBoardDetailUI(bean: BoardItemBean) {
        if (TextUtils.isEmpty(bean.replyUserInfoVo.headImg)) {
            binding.commentDetailIvAvatar.setImageResource(R.drawable.img_comm_avatar)
        } else {
            ImageLoader.loadCircle(this, bean.replyUserInfoVo.headImg, binding.commentDetailIvAvatar)
        }
        binding.commentDetailTvNickname.text = bean.replyUserInfoVo.nickName
        binding.commentDetailTvNickname.text = bean.createTime
        binding.commentDetailTvNickname.text = bean.content

        binding.commentDetailTvReport.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                with(ReportDialog(this)) {
                    btnConfirm.setOnClickListener {
                        if (TextUtils.isEmpty(reportCause)) {
                            showToast("举报原因不能为空！")
                            return@setOnClickListener
                        }
                        reportViewModel.setPostReport(
                            AppBackgroundInfo.instance.userBean!!.userId, bean.replyUserInfoVo.userId,
                            reportCause, bean.id, 1
                        )
                        dismiss()
                    }
                    show()
                }
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        if (bean.contentImgs.size > 0) {
            binding.commentDetailNgvDisplay.run {
                visibility = View.VISIBLE
                setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 200)
                mAdapter.dataList = bean.contentImgs
                mAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
                    override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {

                    }

                    override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                        data?.apply {
                            showImgsPreview(this@BoardDetailActivity, bean.contentImgs, bean.contentImgs.indexOf(this))
                        }
                    }

                    override fun onImageDeleted(position: Int, data: String?) {
                    }
                })
                adapter = mAdapter
            }
        }

        if (bean.children.isNullOrEmpty()) {
            binding.commentDetailLlEmpty.visibility = View.VISIBLE
            binding.commentDetailRecyclerView.visibility = View.GONE
        } else {
            binding.commentDetailLlEmpty.visibility = View.GONE
            binding.commentDetailRecyclerView.visibility = View.VISIBLE
        }

        itemAdapter.setList(bean.children)

        binding.commentDetailBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance()
                    .build(RouterPath.Personal.PAGE_PERSONAL_COMMENT_REPLY)
                    .withObject(AppConstants.COMMENT_ITEM_BEAN, bean)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }
    }

    private fun fetchBoardDetailList() {
        boardViewModel.getBoardDetail(boardUserId, boardId)
    }
}